package solution1.demo1201.demo_other;

import java.io.*;
import java.util.Arrays;

public class ChangeTool {

    public static byte[] toBytes(Object data) {
        try(ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream)) {
            objectOutputStream.writeObject(data);
            return byteArrayOutputStream.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static Object fromBytes(byte[] data) {
        try(ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
            ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream)) {
            return objectInputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }

}

class Main {
    public static void main(String[] args) {
        Demo1 demo1 = new Demo1();
        demo1.setName("cyk");
        demo1.setAge(20);
        byte[] payload = ChangeTool.toBytes(demo1);
        System.out.println("转化为二进制数据！ payload: " + Arrays.toString(payload));
        Demo1 payloadDemo1 = (Demo1) ChangeTool.fromBytes(payload);
        System.out.println("获取到转化以后的数据！payload: " + payloadDemo1);
    }
}
